//
//  BZCureTwoVC.m
//  QuickCure
//
//  Created by brice Mac on 16/9/13.
//  Copyright © 2016年 haoge. All rights reserved.
//



#import "BZCureTwoVC.h"
#import "Masonry.h"
#import "BZBingFaCell.h"
#import "BZSearchModel.h"
#import "NSString+pinyin.h"
#import "BZCureModel.h"

@interface BZCureTwoVC ()

@property(strong,nonatomic)NSMutableArray *btnArray;

@property(strong,nonatomic)NSString *commitStr;

/** 存储模型的数组 */
@property (nonatomic, strong) NSMutableArray *saveDataList;

/** 搜索数组 */
@property (nonatomic, strong) NSMutableArray *searchDataList;

/** 临时数组 */
@property (nonatomic, strong) NSMutableArray *tempModelList;

/** 是否在搜索状态 */
@property (nonatomic, assign) BOOL isSearchState;

@end

@implementation BZCureTwoVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.tableView registerClass:[BZBingFaCell class] forCellReuseIdentifier:@"list"];
    [self.tableView registerClass:[BZBingFaCell class] forCellReuseIdentifier:@"list1"];
    [self.tableView registerClass:[BZBingFaCell class] forCellReuseIdentifier:@"list2"];
    
    [self setupUI];
    
    
        
    if (self.listArray.count) {
        
        if ([self.listArray[0] isKindOfClass:[NSDictionary class]]) {
            
            [self reloadDataModel];
        }
    }

    [self setUpLeftButtonItem];
    
}

-(void)setupUI{
    
    self.tableView.tableFooterView = [UIView new];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 监听TextField值改变，执行的方法
- (void)textChange:(NSNotification *)note{
    UITextField *textField = (UITextField *)[note object];
    // 搜索内容
    [self startSearch:textField.text];
}

#define kScreenW [UIScreen mainScreen].bounds.size.width
#pragma mark - 数据源 、代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //如果想自定义更多，就把noResultLab 换成一个大的BJView，里面再填充很多个小的控件
    UIView *noResultView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    UILabel *noResultLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, kScreenW, 40)];
    [noResultView addSubview:noResultLab];
    noResultLab.font = [UIFont systemFontOfSize:20];
    noResultLab.textColor = [UIColor lightGrayColor];
    noResultLab.textAlignment = NSTextAlignmentCenter;
    noResultView.hidden = YES;
    noResultLab.text = @"抱歉！没有搜索到相关数据";
    tableView.backgroundView = noResultView;
    if (_isSearchState) {
        if (self.searchDataList.count > 0) {
            noResultView.hidden = YES;
            return self.searchDataList.count;
        }else{
            noResultView.hidden = NO;
            return 0;
        }
    }else{
        return self.listArray.count;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    BZCureModel
    id dic = self.listArray[indexPath.row];
    
    BZBingFaCell *cell = [tableView dequeueReusableCellWithIdentifier:[BZBingFaCell getReuseId:dic] forIndexPath:indexPath];
    
    if ([self.listArray[indexPath.row] isKindOfClass:[BZCureModel class]]) {
        
        self.tableView.allowsSelection = NO;
        
        BZCureModel *model = (BZCureModel *)dic;
        
        cell.model = model;
        
    }
    
    if ([self.listArray[indexPath.row] isKindOfClass:[NSDictionary class]]) {
        
        if ([dic objectForKey:@"ci3_name"]){
            
            BZSearchModel *dataMo = nil;
            if (self.saveDataList.count) {
                if (_isSearchState) {
                    dataMo = self.searchDataList[indexPath.row];
                }
                else {
                    dataMo = self.saveDataList[indexPath.row];
                }
            }
            cell.lb_title.text = dataMo.name;
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *selected = nil;
    if (_isSearchState) {
        if (self.tempModelList.count) {
            BZSearchModel *model = self.tempModelList[indexPath.row];
            selected = model.name;
        }
    }
    else {
        BZSearchModel *model = self.saveDataList[indexPath.row];
        selected = model.name;
    }
    if (self.dataBlock) {
        self.dataBlock(selected);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark
#pragma mark - 回车后回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.searchBar resignFirstResponder];
    return YES;
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.searchBar resignFirstResponder];
}

#pragma mark - 开始搜索
-(void)startSearch:(NSString *)string{
    
    if (self.searchDataList.count) {
        [self.searchDataList removeAllObjects];
    }
    NSString *key = string.lowercaseString;
    NSMutableArray *tempModelList = [NSMutableArray array];
    _tempModelList = tempModelList;
    if (![key isEqualToString:@""] && ![key isEqual:[NSNull null]] && key != nil) {
        
        [self.saveDataList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            BZSearchModel *searchModel = self.saveDataList[idx];
            
            //担心框架有时候会误转，再次都设置转为小写
            NSString *name = searchModel.name.localizedLowercaseString;
            NSString *namePinyin = searchModel.namePinYin.localizedLowercaseString;
            NSString *nameFireLetter = searchModel.nameFirstLetter.localizedLowercaseString;
            
            //判断输入字符在搜索列表中的范围
            NSRange rang1 = [name rangeOfString:key];
            
            if (rang1.length > 0) {
                
                [tempModelList addObject:searchModel];
            }else{
                if ([nameFireLetter containsString:key]) {
                    
                    [tempModelList addObject:searchModel];
                    
                }else{
                    if ([nameFireLetter containsString:[key substringToIndex:1]]) {
                        
                        if ([namePinyin containsString:key] ) {
                            
                            [tempModelList addObject:searchModel];
                        }
                    }
                }
            }
        }];
        
        [tempModelList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            if (![self.searchDataList containsObject:tempModelList[idx]]) {
                
                [self.searchDataList addObject:tempModelList[idx]];
            }
        }];
        
        self.isSearchState = YES;
    }else{
        
        self.isSearchState = NO;
    }
    
    [self.tableView reloadData];
}

#pragma mark
#pragma mark - 刷新数据
- (void)reloadDataModel {
    NSArray *nameArr = self.listArray;
    
    for (int i = 0; i < nameArr.count; ++i) {
        
        BZSearchModel *searchModel = [[BZSearchModel alloc] init];
        
        NSDictionary *dic = nameArr[i];
        //转拼音
        NSString *PinYin =  [dic[@"ci3_name"] transformToPinyin];
        
        //首字母
        NSString *FirstLetter = [dic[@"ci3_name"] transformToPinyinFirstLetter];
        
        
        searchModel.name = dic[@"ci3_name"];
        searchModel.namePinYin = PinYin;
        searchModel.nameFirstLetter = FirstLetter;
        
        [self.saveDataList addObject:searchModel];
    }
    [self.tableView reloadData];
}


#pragma mark
#pragma mark - Lazy
- (NSMutableArray *)saveDataList{
    if (_saveDataList == nil) {
        _saveDataList = [[NSMutableArray alloc] init];
    }
    return _saveDataList;
}

- (NSMutableArray *)searchDataList{
    if (_searchDataList == nil) {
        _searchDataList = [[NSMutableArray alloc] init];
    }
    return _searchDataList;
}


#pragma mark
#pragma mark - 记录订阅信息的数组
- (NSMutableArray *)btnArray{
    if (!_btnArray) {
        _btnArray = [NSMutableArray arrayWithCapacity:self.listArray.count];
    }
    return _btnArray;
}

#pragma mark
#pragma mark - 提交订阅信息
- (void)rightButtonClick {
    
    NSMutableString *mString = [NSMutableString string];
    [self.listArray enumerateObjectsUsingBlock:^(BZCureModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.load) {
            if (![mString containsString:obj.complication_name]) {
                [mString appendFormat:@"%@、",obj.complication_name];
            }
        }
    }];
    
    if (mString.length) {
        self.commitStr = [mString substringToIndex:mString.length-1];
    }
    //    NSLog(@"%@",self.commitStr);
    if (self.dataBlock) {
        self.dataBlock(self.commitStr);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}


/*!
 *  默认修改了左上角的item值
 */
- (void)setUpLeftButtonItem{
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
    [leftBtn setImage:[UIImage imageNamed:@"jiantou"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
}

-(void)goBack{
    [self.navigationController popViewControllerAnimated:YES];
}

@end

